import axios from 'axios';
// import { ElNotification, ElMessageBox } from 'element-plus';
// import sysConfig from "@/config";
// import tool from '@/utils/tool';
import { Dialog, Toast } from 'vant';
//import router from '../router';
 
// HTTP response 拦截器
axios.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    if (error.response) {
      Toast.clear();
      if (error.response.status === 404) {
        Dialog.alert({
          title: '请求错误',
          message: "Status:404，正在请求不存在的服务器记录！"
        });
      } else if (error.response.status === 500) {
        Dialog.alert({
          title: '请求错误',
          message: error.response.data.message || "Status:500，服务器发生错误！"
        });
      } else if (error.response.status === 401) {
        // ElMessageBox.confirm('当前用户已被登出或无权限访问当前资源，请尝试重新登录后再操作。', '无权限访问', {
        // 	type: 'error',
        // 	closeOnClickModal: false,
        // 	center: true,
        // 	confirmButtonText: '重新登录'
        // }).then(() => {
        // 	//router.replace({ path: '/login' });
        // })
        // 	.catch(() => { })
        Dialog.alert({
          title: '请求错误',
          message: error.response.data.message || "Status:500，服务器发生错误！"
        });
      } else {
        Dialog.alert({
          title: '请求错误',
          message: error.message || `Status:${error.response.status}，未知错误！`
        });
      }
    } else {
      Dialog.alert({
        title: '请求错误',
        message: "请求服务器无响应！"
      });
    }

    return Promise.reject(error.response);
  }
);

const http = {
  /** get 请求
   * @param  {接口地址} url
   * @param  {请求参数} params
   * @param  {参数} config
   */
  get: function (url, params = {}, config = {}) {
    return new Promise((resolve, reject) => {
      let defaultSet = process.env.NODE_ENV === 'production' ? {} : { org_id: 192, studId: sessionStorage.nowChild }
      if (sessionStorage.baseUser) {
        const user = JSON.parse(sessionStorage.baseUser)
        if (user.orguser) {
          defaultSet = {
            'token': user.token,
            'udid': user.udid,
            'user_id': user.orguser.user_id,
            'user_name': user.orguser.parent == null ? user.orguser.teacher.tech_name : user.orguser.parent.parent_name,
            'org_id': user.orguser.org_id,
            'orgId': user.orguser.org_id,
            'identity': user.orguser.identity,
            'version': 3,
            'studId': user.orguser.identity === 1 ? "" : sessionStorage.nowChild
          }
        } else { 
          defaultSet = {
            'token': user.token,
            'udid': user.udid,
            'user_id': user.orgusers[0].user_id,
            'user_name': user.orgusers[0].parent == null ? user.orgusers[0].teacher.tech_name : user.orgusers[0].parent.parent_name,
            'org_id': user.orgusers[0].org_id,
            'identity': user.orgusers[0].identity,
            'version': 3,
            'studId': user.orgusers[0].identity === 1 ? "" : sessionStorage.nowChild
          }
        }
       
      }
      axios({
        method: 'get',
        url: url,
        params: Object.assign(defaultSet, params),
        ...config
      }).then((response) => {
        resolve(response.data);
      })
        .catch((error) => {
          reject(error);
        })
    })
  },

  /** post 请求
   * @param  {接口地址} url
   * @param  {请求参数} data
   * @param  {参数} config
   */
  post: function (url, data = {}, config = {
    headers: {
      //'Content-Type': 'multipart/form-data'
      //'Content-Type':'application/x-www-form-urlencoded'
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  }) {
    return new Promise((resolve, reject) => {
      let defaultSet = process.env.NODE_ENV === 'production' ? {} : { org_id: 192, studId: sessionStorage.nowChild }
      if (sessionStorage.baseUser) {
        const user = JSON.parse(sessionStorage.baseUser)
        defaultSet = {
          'token': user.token,
          'udid': user.udid,
          'user_id': user.orguser.user_id,
          'user_name': user.orguser.parent == null ? user.orguser.teacher.tech_name : user.orguser.parent.parent_name,
          'org_id': user.orguser.org_id,
          'identity': user.orguser.identity,
          'version': 3,
          'studId': user.orguser.identity === 1 ? "" : sessionStorage.nowChild
        }
      }
      let newData = null;
      let upConfig = null;
      if (data.entries) {
        //上传 
        newData = data;
        for (const attr in defaultSet) {
          newData.append(attr, defaultSet[attr])
        }
        upConfig = {
          method: 'post',
          url: url,
          data: newData,
          ...config
        }
      } else {
        const dealData = Object.assign(defaultSet, data)
        newData = new FormData();
        for (const attr in dealData) {
          newData.append(attr, dealData[attr])
        }
        let newUrl = '';
        for (const key in dealData) {
          newUrl += `${key}=${dealData[key]}&`
        }
          
        upConfig = {
          method: 'POST',
          url: url,
          data: newUrl,
          params: {},
          ...config
        }
      }

      axios(upConfig).then((response) => {
        resolve(response.data);
      })
        .catch((error) => {
          reject(error);
        })
    })
  },

  /** delete 请求
   * @param  {接口地址} url
   * @param  {请求参数} data
   * @param  {参数} config
   */
  delete: function (url, data = {}, config = {}) {
    return new Promise((resolve, reject) => {
      axios({
        method: 'delete',
        url: url,
        data: data,
        ...config
      }).then((response) => {
        resolve(response.data);
      })
        .catch((error) => {
          reject(error);
        })
    })
  },
  /** jsonp 请求
   * @param  {接口地址} url
   * @param  {JSONP回调函数名称} name
   */
  jsonp: function (url, name = 'jsonp') {
    return new Promise((resolve) => {
      const script = document.createElement('script')
      const _id = `jsonp${Math.ceil(Math.random() * 1000000)}`
      script.id = _id
      script.type = 'text/javascript'
      script.src = url
      window[name] = (response) => {
        resolve(response)
        document.getElementsByTagName('head')[0].removeChild(script)
        try {
          delete window[name];
        } catch (e) {
          window[name] = undefined;
        }
      }
      document.getElementsByTagName('head')[0].appendChild(script)
    })
  },
  //获取地址栏参数
  getUrlParam: function (paraName, newUrl) {
    var url = newUrl || document.location.toString();
    var arrObj = url.split("?");
    if (arrObj.length > 1) {
      var arr;
      for (let j = 1; j < arrObj.length; j++) {
        var arrPara = arrObj[j].split("&");
        for (var i = 0; i < arrPara.length; i++) {
          arr = arrPara[i].split("=");
          if (arr != null && arr[0] === paraName) {
            return arr[1];
          }
        }
      }
      return "";
    } else {
      return "";
    }
  }
}
export default http;
